const domain = 'https://testmp.ishalou.com'
//const domain = 'https://saas.ishalou.com'
import jsonBig from 'json-bigint'

function httpCall(api, method, params, callback) {
  let url = domain + api
  let contentType = "application/json";
  let header = {
    "Content-Type": contentType,
  }
  if (getApp().globalData.Authorization) {
    header.Authorization = getApp().globalData.Authorization
  }
  wx.request({
    url: url,
    data: params = null ? {} : params,
    header: header,
    method: method,
    timeout: 20000,
    dataType: '其他',
    success: function (res) {
      const json = jsonBig({
        storeAsString: true
      })
      try {
        let result = json.parse(res.data)
        console.log(result)
        callback(result)
      } catch (e) {
        console.log(e)
        callback(res.data)
      }

    },
    fail: function (res) {
      console.log('httpcall fail:', {
        method,
        url: url,
        params: params,
        res: res,
        header: header
      })
      callback(res.data)
    }
  })
}

/**
 * 排序
 */
function objKeySort(obj) { //排序的函数
  var newkey = Object.keys(obj).sort(); //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
  for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj; //返回排好序的新对象
}

function httpGet(api, params, callback) {
  this.httpCall(api, 'get', params, callback);
}

function httpPost(api, params, callback) {
  this.httpCall(api, 'post', params, callback);
}

module.exports = {
  httpGet: httpGet,
  httpPost: httpPost,
  httpCall: httpCall
}